var db = require('../model');
var utils = require('../utils');
var crypto = require('crypto');
var aes256 = require('nodejs-aes256');
var nodemailer = require('nodemailer');

//移动端注册不需要验证邮箱，但是需要验证
module.exports = {
  register:function(req,res,next){
    var nick = req.body.nick,
        accounts = req.body.accounts,
        pwd = req.body.pwd;
    if(!nick || !accounts || !pwd){
      return next('昵称，账号，密码不能为空');
    }
    if(nick.length > 20){
      return next('昵称不能大于20个字符');
    }
    if(accounts.length > 50){
      return next('邮箱不能大于50个字符');
    }
    if(!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(accounts)){
      return next('邮箱格式不正确');
    }
    if(pwd.length > 30 || pwd.length < 6){
      return next('密码不能小于6位大于30位');
    }
    //不激活邮箱只允许浏览，不允许调用post,邮箱未激活，不允许登录PC版本。
    db.user.findOne({
      accounts:accounts
    }).then((ret)=>{
      if(ret){
        return next('邮箱名重复');
      }else{
         var md5 = crypto.createHash('md5');
         md5.update(pwd);
         pwd = md5.digest('hex');
         db.ids.findOneAndUpdate({
           name:'users'
         },{
           '$inc':{
             id:1
           }
         }).then(ret=>{
            var newuser = new db.user({
               created_at:Date.now(),
               lastlogintime:new Date().valueOf(),
               nick:nick,
               pwd:pwd,
               accounts:accounts,
               id:ret.id,
               from:'app',
               emailnotallow:true //有这个字段的一律不允许调用post和登录pc版本
            }).save().then((ret)=>{
               //发邮件通知
               var code = JSON.stringify([nick,accounts])//加密验证code
               code = aes256.encrypt(config.secret,code);
               var baseURL = isDev ? 'http://' + config.domain + ':' + config.port : 'http://'+config.domain;
               var activeURL = baseURL + '/active?code='+encodeURIComponent(new Buffer(code).toString('base64'));
               var _conf = {
                   from: 'admin <admin@tuer.me>',
                   to:accounts,
                   subject:nick + '欢迎注册兔耳日记！',
                   html:'<p>APP端注册成功，激活邮箱链接:<a href="'+activeURL+'">'+activeURL+'</a></p>'
               };
               try{
                  let transporter = nodemailer.createTransport({
                     sendmail: true,
                     newline: 'unix',
                     path: '/usr/sbin/sendmail'
                  });
                  transporter.sendMail(_conf, function(err, success) {
                    if(err) console.log(err)
                  });
               }catch(e){
                 console.log(e);
               }
              res.json(utils.formatResult({status:'success'}));
            });
         },next);
      }
    },next);
  },
  active:function(req,res,next){
    var code = req.query.code;
    if(!code){
      return next('illegal request');
    }
    try{
      code = new Buffer(code,'base64').toString('ascii');
      code = aes256.decrypt(config.secret,code);
      code = JSON.parse(code);
    }catch(e){
      return next('illegal request'); 
    }
    db.user.findOne({
      accounts:code[1]
    }).then(ret=>{
      if(ret && ret.emailnotallow === true){
        db.user.update({accounts:code[1]},{emailnotallow:false}).then(()=>{
            res.setHeader('Content-Type',"text/html;charset=utf-8");
            res.end('验证成功，感谢您的激活，返回登录 <a href="www.tuer.me">Tuer.me</a>'); 
        },next);
      }else{
        return next('illegal request');
      }
    },next);
  }
};
